//
//  YiChatClient.m
//  onlineCustoSDK
//
//  Created by 曹宗华 on 2017/12/8.
//  Copyright © 2017年 com.netinfosz. All rights reserved.
//

#import "YiChatClient.h"
#import "DES3Util.h"
static  YiChatClient  *instance=nil;
@interface YiChatClient()
{
    ClientInfo *clientinfo;
}
@property(nonatomic,copy)successBlock  sucBlock;
@property(nonatomic,copy)successBlock  sucBlock2;
@property(nonatomic,copy)successBlock  sucBlock3;
@property(nonatomic,copy)failureBlock  failBlock;
@end
@implementation YiChatClient
+(instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance=[[self alloc] init];
    });
    return instance;
}
- (void)setHost:(NSString *)host
{
    if(_host!=host)
    {
        _host=host;
    }
}
- (void)setPort:(NSString *)port
{
    
    if(_port!=port)
    {
        _port=port;
    }
}
//- (NSString*)getVisitorName
- (void)getVisitorNameSuccess:(successBlock)sucBlock fail:(failureBlock)failBlock
{
      HttpRequest  *request=[[HttpRequest alloc] init];
    __block NSString *username=nil;
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/getVisitorUsername",_host];
//    ICLog(@"url:%@",urlStr);
    self.sucBlock=sucBlock;
    self.failBlock =failBlock;
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"getVisitorUsername",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@ "msgBody":[NSNull null]};
    NSString *paramStr=[paramDic jsonString];
    ICLog(@"%@\n%@",paramDic,paramStr);
    [request post:urlStr params:paramStr finish:^(NSString *info) {
//        ICLog(@"访客生产一个用户名:%@",info);
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0) {
            username=returnDic[@"resultData"][@"username"];
//            ICLog(@"username:%@",username);
            self.sucBlock(username);
            self.username=username;
//            [[NSUserDefaults standardUserDefaults] setObject:username forKey:@"username"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//            [self visitorLogin];
           
            
        }
        ICLog(@"获取用户名返回结果:%@",returnDic);
    } failure:^(NSError *error) {
        self.failBlock(error);
        ICLog(@"错误描述:%@",error.localizedDescription);
    }];
    
    if (username!=nil)
    {
//        return username;
    }
//    return nil;
}
//- (void)visitorLogin:(NSString*)username
- (void)visitorLogin:(NSString*)username Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
     HttpRequest  *request=[[HttpRequest alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/visitorLogin",_host];
    ICLog(@"url:%@",urlStr);
    self.username=username;
    self.sucBlock2=sucBlock;
    self.failBlock =failBlock;
     __block NSString *token=nil;
    __block NSString *userId=nil;
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"visitorLogin",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"username":username}};
    NSString *paramStr=[paramDic jsonString];
    ICLog(@"%@\n%@",paramDic,paramStr);
    [request post:urlStr params:paramStr finish:^(NSString *info) {
//        ICLog(@"使用访客用户名登录系统:%@",info);
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            token=returnDic[@"resultData"][@"token"];
            userId=returnDic[@"resultData"][@"userId"];
            self.token=token;
            self.userId=userId;
            self.sucBlock2(info);
           
            ICLog(@"token:%@\n userId:%@",token,userId);
            [[NSUserDefaults standardUserDefaults] setObject:username forKey:@"token"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            ICLog(@"登录结果:%@",returnDic);
//            [self createSocket];  //连接websocket
//            [self createSession];
        }
        
    } failure:^(NSError *error) {
        ICLog(@"登录错误描述:%@",error.localizedDescription);
        self.failBlock(error);
       
    }];
}
- (void)createSessionSuccess:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    
}
/**
 *skillId 请求建立会话的技能队列，一般无特殊需求填1
 *level 客户等级 默认是1
 *callData 随路数据 @{@"f1":@"v1",@"f2":@"v2"}
 *
 */
- (void)createSessionSkillId:(NSString *)skillId Level:(int)level callData:(NSDictionary*)callData Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    NSString *uuid=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
//    clientinfo=[[ClientInfo alloc] init];
    NSString *clientInfoStr=[[ClientInfo shareInstance] getAppClientInfo];
    ICLog(@"uuid:%@,clientInfo:%@",uuid,clientInfoStr);
    if(!_skillId)
    {
        ICLog(@"skillId为空");
        return;
    }
    if(!_appKey)
    {
        ICLog(@"appKey为空");
        return;
    }
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/createSession",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"2.0",@"msgType":@"createSession",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"skillId":skillId,@"appKey":_appKey,@"channelId":@"27",@"level":@(1),@"callData":callData,@"clientInfo":clientInfoStr }};
    NSString *paramStr=[paramDic jsonString];
    
    ICLog(@"创建会话参数:%@",paramDic);
    self.sucBlock3=sucBlock;
    self.failBlock =failBlock;
    self.request2=[[HttpRequestWithToken alloc] init];
    //    [self.request2.request setValue:_token forHTTPHeaderField:@"Authorization"];
    [self.request2.request addValue:self.token forHTTPHeaderField:@"Authorization"];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        ICLog(@"建立会话:%@",info);
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            self.sessionId=returnDic[@"resultData"][@"sessionId"];
            [[NSUserDefaults standardUserDefaults] setObject:_sessionId forKey:@"sessionId"];
//            ICLog(@"sessionId:%@",self.sessionId);
            //            [self sendMessage];
            self.sucBlock3(info);
        }else if ([returnDic[@"response"][@"resultCode"] intValue]==100009)
        {
            ICLog(@"Token异常");
//            [self visitorLogin];
            self.sucBlock3(info);
            
        }else if ([returnDic[@"response"][@"resultCode"] intValue]==100010)
        {
            ICLog(@"已经申请过建立会话");
            self.sessionId=returnDic[@"resultData"][@"sessionId"];
            [[NSUserDefaults standardUserDefaults] setObject:_sessionId forKey:@"sessionId"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            ICLog(@"sessionId:%@",self.sessionId);
            //            [self dropSession];
            //            [self createSession];
            //            [CCDemoUtil showAlertWithTitle:@"提示" content:@"sessionId"];
            //            [self visitorLogin];
            self.sucBlock3(info);
            
        }else if ([returnDic[@"response"][@"resultCode"] intValue]==100011)
        {
            ICLog(@"已经申请过建立会话，系统已自动结束");
            self.sucBlock3(info);
        }else if ([returnDic[@"response"][@"resultCode"] intValue]==100006)
        {
            ICLog(@"当前非服务时间");
            self.sucBlock3(info);
        }
        
    } failure:^(NSError *error) {
        ICLog(@"创建会话错误描述:%@",error.localizedDescription);
        self.failBlock(error);
    }];
}
/**
 *参数:(NSString*)url
 *功能：下载文件
 *返回值:(NSData*)data
 **/
- (NSData*)getFile:(NSString*)url
{
//    self.request=[[HttpRequest alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/getFile?filePath=%@",_host,url];
//    ICLog(@"下载地址:%@",urlStr);
    NSURL *URL=[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:60];
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//    image=[UIImage imageWithData:received];
    ICLog(@"下载完成");
    return [received copy];
}


/**
 *参数1:(NSData *)data
 *参数2:(NSString *)fileType
 *功能：上传图片或语音
 **/
- (void)uploadFile:(NSData *)data type:(NSString *)fileType
{
    //如果是iOS 7调用

    if(self.token==nil)
    {
         ICLog(@"token为空:%@",self.token);
        return;
    }
   
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/upload",_host];
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
//   [manager.requestSerializer setValue:@"multipart/form-data; boundary=BOUNDARY" forHTTPHeaderField:@"Content-Type"];
    //    NSDictionary *paramdic=@{@"Authorization":self.token};
    //    [manager.requestSerializer setValue:self.token forHTTPHeaderField:@"Authorization"];
//    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"en-US" forHTTPHeaderField:@"Accept-Language"];
    [manager.requestSerializer setValue:@"multipart/form-data; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

//    [manager.requestSerializer setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
    manager.responseSerializer.acceptableContentTypes= [NSSet setWithObjects:@"application/json",@"application/form-data",
                                                        @"text/html",
                                                        @"image/jpeg",
                                                        @"image/png",
                                                        @"application/octet-stream",
                                                        @"text/json",@"text/plain",
                                                        nil];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] == 7.1) {
        
        //        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [manager.requestSerializer setValue:@"en-US" forHTTPHeaderField:@"Accept-Language"];
        [manager.requestSerializer setValue:@"multipart/form-data; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
       
    }
    
    [manager POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *tokenData=[self.token dataUsingEncoding:NSUTF8StringEncoding];
        [formData appendPartWithFormData:tokenData name:@"token"];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat =@"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = @"";
        NSString *mimeType=@"";
        if([fileType isEqualToString:@"voice"])
        {
            fileName=[NSString stringWithFormat:@"%@.wav", str];
            mimeType=[NSString stringWithFormat:@"%@/wav",fileType];
        }else  if([fileType isEqualToString:@"image"])
        {
            fileName = [NSString stringWithFormat:@"%@.png", str];
            mimeType=[NSString stringWithFormat:@"%@/png",fileType];
        }
        
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:data
                                    name:@"file"
                                fileName:fileName
                                mimeType:mimeType];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        ICLog(@"上传结果:%@,%@",dic,dic[@"resultData"]);
        if ([dic[@"response"][@"resultCode"] intValue]==0)
        {
            
            if([dic[@"resultData"] isEqual:[NSNull null]]||dic[@"resultData"]==nil)
            {
                ICLog(@"返回了空值");
                return ;
            }
            NSString *url=dic[@"resultData"][@"attachment"];
            ICLog(@"ur值:%@",url);
            NSMutableDictionary *content=[NSMutableDictionary dictionary];
            if([url hasSuffix:@".png"])
            {
                [content setObject:url forKey:@"picUrl"];
                NSString *contentJson=[content jsonString];
                ICLog(@"picUrl:%@",contentJson);
                [self sendMessage:contentJson type:fileType];
            }else if([url hasSuffix:@".wav"])
            {
                [content setObject:@"voice" forKey:@"msgType"];
                [content setObject:url forKey:@"mediaUrl"];

                if (self.voiceLength != nil) {
                    [content setObject:self.voiceLength forKey:@"mediaLength"];
                }else
                {
                    [content setObject:@"4" forKey:@"mediaLength"];
                }
                NSString *contentJson=[content jsonString];
                ICLog(@"wav:%@",contentJson);
                [self sendMessage:contentJson type:fileType];
            }
//            ICLog(@"发送url地址完成");
        }else if ([dic[@"response"][@"resultCode"] intValue]!=0)
        {
            ICLog(@"resultMsg:%@",dic[@"response"][@"resultMsg"] );
            return ;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败
        ICLog(@"上传失败Error:%@",error.localizedDescription);
    }];
    
}

-(void)iOS7UploadFileWithData:(NSData *)data
{

    self.request2=[[HttpRequestWithToken alloc] init];
NSString *urlStr=[NSString stringWithFormat:@"%@/service/upload",_host];

    
    NSDictionary *paramDic=@{@"Content-Type":@"multipart/form-data",@"file":data};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            ICLog(@"dropSession:%@",returnDic[@"response"][@"resultMsg"]);
        }
        
    } failure:^(NSError *error) {
        
    }];
    
    
    
}







- (void)dropSession
{
    self.request2=[[HttpRequestWithToken alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/dropSession",_host];
    if (self.sessionId==nil||self.sessionId.length==0)
    {
        ICLog(@"sessionid为空");
        return;
    }
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"dropSession",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"sessionId":self.sessionId}};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            ICLog(@"dropSession:%@",returnDic[@"response"][@"resultMsg"]);
        }
        
    } failure:^(NSError *error) {
        
    }];
}
- (void)dropSession:(NSString*)sessionId Success:(successBlock)sucBlock
{
    self.request2=[[HttpRequestWithToken alloc] init];
    self.sucBlock=sucBlock;
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/dropSession",_host];
    if (sessionId==nil||sessionId.length==0)
    {
        ICLog(@"sessionid为空");
        return;
    }
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"dropSession",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"sessionId":sessionId}};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
//            ICLog(@"dropSession:%@",returnDic[@"response"][@"resultMsg"]);
            self.sucBlock(info);
            
        }
        
    } failure:^(NSError *error) {
        
    }];
}
- (void)sendMessage:(NSString*)content type:(NSString*)type
{
    if(content==nil||content.length==0)
    {
        return;
    }
    if(self.sessionId==nil||self.sessionId==0)
    {
        ICLog(@"sessionId为空");
        return;
    }
    if (self.token==nil||self.token.length==0)
    {
        ICLog(@"token为空");
        return;
    }
    self.request2=[[HttpRequestWithToken alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/sendMessage",_host];
    NSDictionary *paramDic=nil;
//    if([type isEqualToString:@"custVerify"])
//    {
//        NSData *data=[content dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *contentDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//        paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"sendMessage",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"sessionId":self.sessionId,@"content":contentDic,@"type":type}};
//    }else
    {
        paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"sendMessage",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"sessionId":self.sessionId,@"content":content,@"type":type}};
    }
    
    NSString *paramStr=[paramDic jsonString];
    ICLog(@"发送消息的参数:%@",paramStr);
    //    [self.request2.request addValue:self.token forHTTPHeaderField:@"Authorization"];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        if(info==nil)
        {
            return ;
        }
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            ICLog(@"发送消息成功:%@",returnDic[@"response"][@"resultMsg"]);
        }
        ICLog(@"发送消息结果:%@",returnDic);
        
    } failure:^(NSError *error) {
        ICLog(@"发送消息失败:%@",error.localizedDescription);
    }];
}
/**
 *功能:发送回执消息
 *
 *
 **/
- (void)sendReceipt:(NSString*)notifyId
{
    
}
- (void)transferToAgent
{
    ICLog(@"点击了按钮");
    [self transferToAgentCompleted:nil];
    
}

- (void)transferToAgentCompleted:(void (^)(NSError *))cmp {
    self.request2=[[HttpRequestWithToken alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/transferToArtificial",_host];
    if(self.sessionId==nil||self.sessionId.length==0)
    {
        ICLog(@"sessionId为空");
        return;
    }
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"transferToArtificial",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"sessionId":self.sessionId}};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSInteger resultCode = [returnDic[@"response"][@"resultCode"] intValue];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            ICLog(@"transferToArtificial成功:%@",returnDic[@"response"][@"resultMsg"]);
        }else if (resultCode==100011)
        {
            ICLog(@"已经申请过建立会话:%@",returnDic[@"response"][@"resultMsg"]);
        }else if (resultCode==100010)
        {
            ICLog(@"已经申请过建立会话，系统已自动结束:%@",returnDic[@"response"][@"resultMsg"]);
        }else if (resultCode==100009)
        {
            ICLog(@"Token异常:%@",returnDic[@"response"][@"resultMsg"]);
        }else if (resultCode==100000)
        {
//            ICLog(@"通用异常错误码:%@",returnDic[@"response"][@"resultMsg"]);
//        }else if ([returnDic[@"response"][@"resultCode"] intValue]==100000)
//        {
            ICLog(@"通用异常错误码:%@",returnDic[@"response"][@"resultMsg"]);
        }
        
        if (resultCode != 0) {
            NSError *error = [NSError errorWithDomain:NSCocoaErrorDomain code:resultCode userInfo:@{NSLocalizedFailureReasonErrorKey: returnDic[@"response"][@"resultMsg"] ?: @"转人工失败"}];
            !cmp ?: cmp(error);
            if ([self.sdkDelegate respondsToSelector:@selector(onSDKHandleFailed:)] && self.sdkDelegate) {
                [self.sdkDelegate onSDKHandleFailed:error];
            }
        }
        ICLog(@"转人工");
    } failure:^(NSError *error) {
        ICLog(@"转人工失败:%@",error.localizedDescription);
        NSError *err = [NSError errorWithDomain:NSURLErrorDomain code:100000 userInfo:@{NSLocalizedFailureReasonErrorKey: error.localizedDescription}];
        !cmp ?: cmp(err);
        if ([self.sdkDelegate respondsToSelector:@selector(onSDKHandleFailed:)] && self.sdkDelegate) {
            [self.sdkDelegate onSDKHandleFailed:err];
        }
    }];
}

/**
- (void)verifyUserAccount:(NSString*)khbs password:(NSString*)jymm khbslx:(NSString*)khbslx Success:(successBlock)sucBlock
{
    self.sucBlock3=sucBlock;
    self.request=[[HttpRequest alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/work_platform/kjdp_nofilter?returnType=json",_host];
    NSString *czlx=@"14007";
    NSString *bex_codes=khbs.length==10?@"20102905_02":@"20102905_01";
    NSDictionary *paramDic=@{@"service":@"externalSupport",@ "bex_codes":bex_codes,@"selectName":@(1),@"khbs":khbs,@"khbslx":khbslx,@"yjmm":jymm,@"gzzh":@"",@"wxid":@"",@"czlx":czlx};
//    NSString *paramStr=[paramDic jsonString];
    NSMutableArray *ary=[NSMutableArray array];
    NSDictionary *REQ_MSG_dic=@{@"OP_CODE":@"",@"OP_ROLE":@"",@"OP_BRANCH":@"",@"OP_SITE":@"",@"USER_TICKET_INFO":@"",@"OP_WAY":@"1",@"OP_LANGUAGE":@"1",@"OP_PROGRAM":@"menuId",@"SERVER_ID":@"service",@"MSG_ID":@"service"};
   
   
    NSDictionary *dic3=@{@"REQ_MSG_HDR":REQ_MSG_dic,@"REQ_COMM_DATA":paramDic};
    [ary addObject:dic3];
     NSDictionary *dic1=@{@"REQUESTS":ary};
    NSString *param=[dic1 jsonString];
     ICLog(@"接口地址:%@,验证接口参数:%@",urlStr,param);
    NSString *key=@"888888";
    NSString *paramSecurity=[DES3Util encryptUseDES:param key:key];
    ICLog(@"加密后的参数:%@",paramSecurity);
    [self.request post:urlStr params:paramSecurity finish:^(NSString *info) {
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        self.sucBlock3(info);
        ICLog(@"资金帐号验证结果:%@",returnDic);
    } failure:^(NSError *error) {
        ICLog(@"验证失败%@",error.localizedDescription);
    }];
}
- (void)getVerifycodeResult:(result)resultBlock
{
    self.resultBlock=resultBlock;
    srand(time(0));
     float randomNum = (float)(rand() % 100) /100;
    ICLog(@"随机数:%f",randomNum);
    self.request=[[HttpRequest alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/work_platform/kjdp_validate?i=%f",_host,randomNum];
    ICLog(@"验证码url接口:%@",urlStr);
    [self.request get:urlStr params:nil finish:^(NSString *info) {
        ICLog(@"获取验证码返回:%@",info);
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        self.resultBlock(data);
    } failure:^(NSError *error) {
        ICLog(@"获取验证码失败%@",error.localizedDescription);
    }];
    
}
 */
- (void)addVisitorUserinfo:(NSDictionary*)userinfo Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    NSString *username=userinfo[@"username"];
    NSString *password=userinfo[@"password"];
    NSString *niceName=userinfo[@"niceName"];
    self.sucBlock=sucBlock;
    self.failBlock=failBlock;
    if(username==nil||password==nil)
    {
        ICLog(@"帐号或密码不能为空");
        return;
    }
    self.request=[[HttpRequest alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/addVisitor",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"addVisitor",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":userinfo};
    //  @"username":username,@"password":password,@"niceName":niceName
    NSString *paramStr=[paramDic jsonString];
    ICLog(@"addVisitorUserinfo urlStr:%@", urlStr);
    [self.request post:urlStr params:paramStr finish:^(NSString *info) {
        ICLog(@"%@",info);
        self.sucBlock(info);
    } failure:^(NSError *error) {
        ICLog(@"增加用户错误描述:%@",error.localizedDescription);
        self.failBlock(error);
    }];
    
}
- (void)getEvaluationOptionsSuccess:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    self.request2=[[HttpRequestWithToken alloc] init];
    self.sucBlock3=sucBlock;
    self.failBlock=failBlock;
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/getEvaluationOption",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"getEvaluationOption",@"sequenceNo":@"1464148231245",@"validateString":@"XXXXX"},@"msgBody":[NSNull null]};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        self.sucBlock3(info);
    } failure:^(NSError *error) {
        self.failBlock(error);
    }];
}
//评价客服
- (void)evalutionLevel:(int) level Content:(NSString*)evaluationContent Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    self.request2=[[HttpRequestWithToken alloc] init];
    self.sucBlock3=sucBlock;
    self.failBlock=failBlock;
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/evalution",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"evalution",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"transferId":_transferId,@"evaluationLevel":@(level),@"evaluationContent":evaluationContent}};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        self.sucBlock3(info);
    } failure:^(NSError *error) {
        self.failBlock(error);
    }];
}
/**
 *评价客服
 *
 *
 *
 */
- (void)evalutionTransferId:(NSString*)transferId Level:(int) level Content:(NSString*)content Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    self.request2=[[HttpRequestWithToken alloc] init];
    self.sucBlock3=sucBlock;
    self.failBlock=failBlock;
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/evalution",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"evalution",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"transferId":transferId,@"evaluationLevel":@(level),@"evaluationContent":content}};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        self.sucBlock3(info);
    } failure:^(NSError *error) {
        self.failBlock(error);
    }];
    
}
- (void)evaluationRobotAccesssId:(NSString*)accessId Level:(int)level Content:(NSString*)content Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    self.request2=[[HttpRequestWithToken alloc] init];
    self.sucBlock3=sucBlock;
    self.failBlock=failBlock;
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/evalutionRobot",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"evalutionRobot",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"transferId":accessId,@"evaluationLevel":@(level),@"evaluationContent":content}};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        ICLog(@"评价机器人:%@",info);
         self.sucBlock3(info);
    } failure:^(NSError *error) {
         self.failBlock(error);
        
    }];
    
}
- (void)sendMessage:(NSString*)content type:(NSString*)type Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    if(content==nil||content.length==0)
    {
        return;
    }
    if(self.sessionId==nil||self.sessionId==0)
    {
        ICLog(@"sessionId为空");
        return;
    }
    if (self.token==nil||self.token.length==0)
    {
        ICLog(@"token为空");
        return;
    }
    self.sucBlock2=sucBlock;
    self.failBlock=failBlock;
    self.request2=[[HttpRequestWithToken alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/sendMessage",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"sendMessage",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"sessionId":self.sessionId,@"content":content,@"type":type}};
    NSString *paramStr=[paramDic jsonString];
    //    [self.request2.request addValue:self.token forHTTPHeaderField:@"Authorization"];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        if(info==nil)
        {
            return ;
        }
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            ICLog(@"发送消息成功:%@",returnDic[@"response"][@"resultMsg"]);
        }
        ICLog(@"发送消息结果:%@",returnDic);
        self.sucBlock2(info);
    } failure:^(NSError *error) {
        self.failBlock(error);
        ICLog(@"发送消息失败:%@",error.localizedDescription);
    }];
}
- (void)getTokenSuccess:(successBlock)sucBlock
{
    self.sucBlock =sucBlock;
    self.request=[[HttpRequest alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/work_platform/ka_getToken",_host];
    [self.request get:urlStr params:nil finish:^(NSString *info) {
//        ICLog(@"获取token返回:%@",info);
        self.sucBlock(info);
       
    } failure:^(NSError *error) {
        ICLog(@"获取token失败%@",error.localizedDescription);
    }];
}
- (UIImage*)getValidateCode
{
    self.request=[[HttpRequest alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/work_platform/ka_validate?token=%@",_host,_validateToken];
    NSURL *URL=[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:60];
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    UIImage *image=[UIImage imageWithData:received];
    ICLog(@"下载验证码完成");
    return [image copy];
    
}
- (UIImage*)getValidateCodeWithToken:(NSString*)Validatetoken
{
    self.request=[[HttpRequest alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/work_platform/ka_validate?token=%@",_host,Validatetoken];
    NSURL *URL=[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:60];
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    UIImage *image=[UIImage imageWithData:received];
    ICLog(@"下载验证码完成");
    return [image copy];
}
- (void)validateAount:(NSString*)account password:(NSString*)password Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    self.sucBlock3=sucBlock;
    self.request=[[HttpRequest alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/work_platform/ka_tokenValidate",_host];
//    NSDictionary *paramDic=@{@"service":@"externalSupport",@ "bex_codes":@"",@"selectName":@(1),@"khbs":@"",@"khbslx":@"",@"yjmm":@"",@"gzzh":@"",@"wxid":@"",@"czlx":@""};
//    NSDictionary *paramDic=@{@"validateCode":_validateCode,@"token":_validateToken,@"custAcctType":@"Z",@"custAcctNo":account,@"password":password};
//    NSString *paramStr=[paramDic jsonString];
    
    NSString *encodePassword=[password URLEncodedString];
    NSString *param=[NSString stringWithFormat:@"validateCode=%@&token=%@&custAcctType=%@&custAcctNo=%@&password=%@",_validateCode,_validateToken,@"Z",account,encodePassword];
//    NSString *urlparam =[param stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSString *urlparam = [param URLEncodedString];
    [self.request post2:urlStr params:param finish:^(NSString *info) {
        ICLog(@"验证结果1:%@",info);
        self.sucBlock3(info);
        
    } failure:^(NSError *error) {
        ICLog(@"%@",error.localizedDescription);
    }];
    
}
/**
 *资金帐号或信用帐号验证
 *@param custAcctNo    用户名
 *@param password      密码
 *@param validatecode  验证码
 *@param custAcctType  验证类型  资金帐户和信用帐户都传Z（从消息类型为"custVerify"消息中获取）
 *@param token         验证token
 *@param pubkey        RSA加密公钥
 *@param systemcode    系统编码  信用帐户：8888，资金帐户：空
 *@param sucBlock      成功回调
 *@param failBlock     失败回调
 */
//- (void)validateAount:(NSString *)custAcctNo password:(NSString *)password ValidateCode:(NSString *)validatecode CustAcctType:(NSString *)custAcctType Token:(NSString *)token PubKey:(NSString *)pubkey Success:(successBlock)sucBlock fail:(failureBlock)failBlock
- (void)validateAount:(NSString*)custAcctNo password:(NSString*)password ValidateCode:(NSString*)validatecode CustAcctType:(NSString*)custAcctType Token:(NSString*)token PubKey:(NSString*)pubkey Syscode:(NSString*)systemcode Need:(BOOL)feedBack Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    self.sucBlock3=sucBlock;
    self.request=[[HttpRequest alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/work_platform/ka_tokenValidate",_host];
    
     NSString *encriptpassword = [RSAUtil encryptString:password publicKey:pubkey];
    self.custAcctType=custAcctType;
    if(self.custAcctType==nil)
    {
        self.custAcctType=@"Z";
    }
//    NSString *encodePassword=[password URLEncodedString];
     NSString *encodePassword=[encriptpassword URLEncodedString];
    NSString *param=[NSString stringWithFormat:@"validateCode=%@&token=%@&custAcctType=%@&custAcctNo=%@&password=%@&_SYSCODE=%@",validatecode,token,custAcctType,custAcctNo,encodePassword,systemcode];
//    ICLog(@"验证接口参数:%@",param);
    [self.request post2:urlStr params:param finish:^(NSString *info) {
//        ICLog(@"验证结果1:%@",info);
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if([returnDic[@"CODE"] intValue]==0)
        {
            NSString *successInfo=returnDic[@"INFO"];
            NSDictionary *contentDic=@{@"appid":@"14007",@"className":@"text-green",@"content":@"验证成功",@"custAcctType":_custAcctType,@"custid":successInfo,@"msgType":@"custVerify",@"param":@"",@"password":@"",@"phoneNum":_username,@"verifyRes":@(1),@"sendToAgent":@"true"};
            NSString *content=[contentDic jsonString];
            if(feedBack==YES)
            {
                 [self sendMessage:content type:@"custVerify"];
            }
           
        }
//        else  if([returnDic[@"CODE"] intValue]==-3)//2019年0307注释
//        {
//            NSString *successInfo=returnDic[@"INFO"];
//            ICLog(@"验证码-3:%@",successInfo);
//        }
        else
        {
            NSString *successInfo=returnDic[@"INFO"];
            NSString *failureInfo=[NSString stringWithFormat:@"验证失败:%@",successInfo];
            NSDictionary *contentDic=@{@"appid":@"14007",@"className":@"text-red",@"content":failureInfo,@"custAcctType":_custAcctType,@"custid":successInfo,@"msgType":@"custVerify",@"param":@"",@"password":@"",@"phoneNum":_username,@"verifyRes":@(1),@"sendToAgent":@"true"};
            NSString *content=[contentDic jsonString];
            if(feedBack==YES)
            {
                  [self sendMessage:content type:@"custVerify"];
            }
          
        }
        self.sucBlock3(info);
        
    } failure:^(NSError *error) {
        ICLog(@"验证报错:%@",error.localizedDescription);
        self.failBlock(error);
    }];
}
//获取最新会话
- (void)getLatestSessionSuccess:(successBlock) sucBlock fail:(failureBlock)failBlock
{
    if(!_skillId)
    {
        ICLog(@"skillId为空");
        return;
    }
    if(!_appKey)
    {
        ICLog(@"appKey为空");
        return;
    }
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/getLatestSession",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"getLatestSession",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":[NSNull null]};
    NSString *paramStr=[paramDic jsonString];
    
  //  ICLog(@"获取最新会话参数:%@",paramDic);
    self.sucBlock3=sucBlock;
    self.failBlock =failBlock;
//    self.request=[[HttpRequest alloc] init];
       self.request2=[[HttpRequestWithToken alloc] init];
    //    [self.request2.request setValue:_token forHTTPHeaderField:@"Authorization"];
  
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
         self.sucBlock3(info);
    } failure:^(NSError *error) {
          self.failBlock(error);
    }];
}
//增加留言
- (void)addLeftMessage:(NSDictionary*)message Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    NSString *subject=message[@"subject"];
    NSString *content=message[@"content"];
    NSString *attachment=message[@"attachment"];
    NSString *channelId=message[@"channelId"];
    NSString *name=message[@"name"];
    NSString *email=message[@"email"];
     NSString *phone=message[@"phone"];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/addLeftMessage",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"addLeftMessage",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"subjec":subject,@"content":content,@"attachment":attachment,@"sessionId":self.sessionId,@"name":name,@"email":email,@"phone":phone}};
    NSString *paramStr=[paramDic jsonString];
    self.sucBlock3=sucBlock;
    self.failBlock =failBlock;
    //  ICLog(@"获取最新会话参数:%@",paramDic);
   
    //    self.request=[[HttpRequest alloc] init];
    self.request2=[[HttpRequestWithToken alloc] init];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        self.sucBlock3(info);
    } failure:^(NSError *error) {
        self.failBlock(error);
    }];
}
// 机器人反馈
- (void)feedbackRobot:(NSDictionary*)param Success:(successBlock)sucBlock
{
    NSString *question=[param objectForKey:@"question"];
    NSString *answer=[param objectForKey:@"answer"];
    NSString *type=[param objectForKey:@"type"];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/feedbackRobot",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"feedbackRobot",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"question":question,@"answer":answer,@"type":type,@"sessionId":self.sessionId}};
    NSString *paramStr=[paramDic jsonString];
    self.request2=[[HttpRequestWithToken alloc] init];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        sucBlock(info);
    } failure:^(NSError *error) {
        ICLog(@"机器人反馈报错:%@",error.localizedDescription);
    }];
    
}
- (void)continueBusi:(NSString*)code validateInfo:(NSString*)IDinfo Success:(successBlock)sucBlock
{
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/continueBusi",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"feedbackRobot",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"code":code,@"info":IDinfo}};
    NSString *paramStr=[paramDic jsonString];
    self.request2=[[HttpRequestWithToken alloc] init];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        sucBlock(info);
    } failure:^(NSError *error) {
        ICLog(@"继续办理业务报错:%@",error.localizedDescription);
    }];
    
}
//敏感词检测
- (void)detectSensitiveWords:(NSString*)text Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    NSString *urlStr=nil;
    if([[_host componentsSeparatedByString:@":"] count]==3)
    {
         urlStr=[NSString stringWithFormat:@"%@/workinterface/yichat/mgcjc",_host];
    }else if([[_host componentsSeparatedByString:@":"] count]==2)
    {
        if(self.port==nil)
        {
            return;
        }
        NSMutableString *appendURL=[NSMutableString stringWithFormat:@"%@:",_host];
        [appendURL insertString:_port atIndex:appendURL.length];
        urlStr=[NSString stringWithFormat:@"%@/workinterface/yichat/mgcjc",appendURL];
    }
   
//    ICLog(@"appendURL:%@",appendURL);
//    NSString *urlStr=[NSString stringWithFormat:@"%@/workinterface/yichat/mgcjc",appendURL];
//     NSString *urlStr=[NSString stringWithFormat:@"%@/mgcjc",_host];
//    ICLog(@"敏感词接口urlStr:%@",urlStr);
   NSString *param=[NSString stringWithFormat:@"str=%@",text];
//    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
//    [dic setObject:text forKey:@"str"];
//    NSString *paramjson=[dic jsonString];
    HttpRequest *request=[[HttpRequest alloc] init];
    [request post2:urlStr params:param finish:^(NSString *info) {
        sucBlock(info);
    } failure:^(NSError *error) {
        ICLog(@"敏感词检测报错:%@",error.localizedDescription);
        failBlock(error);
    }];
    
}
//获取热点问题
- (void)getHotQuestions:(NSDictionary*)param Success:(successBlock)sucBlock
{
    NSNumber *mode=[param objectForKey:@"mode"];
    NSNumber *channelId=[param objectForKey:@"channelId"];
    NSNumber *size=[param objectForKey:@"size"];
    NSString  *brand=[param objectForKey:@"brand"];
    NSString *type=[param objectForKey:@"type"];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/getHotQuestion",_host];
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"feedbackRobot",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"mode":mode,@"channelId":channelId,@"type":type,@"size":size,@"brand":brand}};
    NSString *paramStr=[paramDic jsonString];
    self.request2=[[HttpRequestWithToken alloc] init];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        sucBlock(info);
    } failure:^(NSError *error) {
        ICLog(@"获取热点问题:%@",error.localizedDescription);
    }];
//     HttpRequest *request=[[HttpRequest alloc] init];
//    [request post2:urlStr params:paramStr finish:^(NSString *info) {
//        sucBlock(info);
//    } failure:^(NSError *error) {
//        ICLog(@"获取热点问题:%@",error.localizedDescription);
//    }];
}
- (void)getQueueInfoSuccess:(successBlock) sucBlock fail:(failureBlock)failBlock
{
    self.request2=[[HttpRequestWithToken alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/getQueueInfo",_host];
    if (self.sessionId==nil||self.sessionId.length==0)
    {
        ICLog(@"sessionid为空");
        return;
    }
    NSDictionary *paramDic=@{@"request":@{@"version":@"1.0",@"msgType":@"getQueueInfo",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"sessionId":self.sessionId}};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            ICLog(@"getQueueInfo:%@",returnDic[@"response"][@"resultMsg"]);
           
        }
         sucBlock(info);
    } failure:^(NSError *error) {
        failBlock(error);
    }];
}
- (void)cancelQueueSuccess:(successBlock)sucBlock
{
    self.request2=[[HttpRequestWithToken alloc] init];
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/cancelQueue",_host];
    if (self.sessionId==nil||self.sessionId.length==0)
    {
        ICLog(@"sessionid为空");
        return;
    }
    NSDictionary *paramDic=@{@"request":@{@"version":@"2.0",@"msgType":@"cancelQueue",@"sequenceNo":@"1464148231245",@"tenantId":@(1),@"validateString":@"XXXXX"},@"msgBody":@{@"sessionId":self.sessionId}};
    NSString *paramStr=[paramDic jsonString];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if ([returnDic[@"response"][@"resultCode"] intValue]==0)
        {
            ICLog(@"cancelQueue:%@",returnDic[@"response"][@"resultMsg"]);
           sucBlock(info);
        }
        
    } failure:^(NSError *error) {
//        failBlock(error);
    }];
}


/// 获取智能提示
/// @param content 用户输入的问题
/// @param channelId 渠道Id
/// @param brand 品牌
/// @param size 获取智能提示的条数
/// @param successBlock successBlock
/// @param failBlock failBlock description
-(void)getSuggestedQuestionWithContent:(NSString *)content ChannelId:(int)channelId Brand:(NSString *)brand Size:(int)size Success:(successBlock)successBlock fail:(failureBlock)failBlock{
   
    if (content == nil || brand == nil) {
        return;
    }
    NSMutableDictionary *bodyDict = [NSMutableDictionary dictionaryWithDictionary:@{
        @"type":@"text",
        @"content":content,
        @"channelId":@(channelId),
        @"size":@(size),
    }];
    
    if (brand != nil) {
        [bodyDict setObject:brand forKey:@"brand"];
    }
 
    NSString *urlStr=[NSString stringWithFormat:@"%@/agentService/getSuggestedQuestion",_host];
    

    NSDictionary *paramDic = @{@"request":@{@"version":@"1.0",@"msgType":@"getSuggestedQuestion",@"sequenceNo": @"1464148231245",@"validateString":@"XXXXX" },@"msgBody":bodyDict.copy};
    
    self.request2=[[HttpRequestWithToken alloc] init];
    NSString *paramStr=[paramDic jsonString];
   
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
         successBlock(info);
    } failure:^(NSError *error) {
        failBlock(error);
    }];
 
}

///// 获取App客户端配置
///// @param appKey appKey
-(void)getAppConfigWithAppKey:(NSString *)appKey
                      Success:(successBlock)successBlock
                         fail:(failureBlock)failBlock{
//    {"request":{"version":"1.0","msgType":"getAppConfig","sequenceNo": "1464148231245","validateString":"XXXXX"},"msgBody":{"appKey":"0a8d41f5f9d44fa1b9e24ab2fd53cfd7"}}
    
    NSString *urlStr=[NSString stringWithFormat:@"%@/service/getAppConfig",_host];
    NSDictionary *paramDic = @{@"request":@{@"version":@"1.0",@"msgType":@"getAppConfig",@"sequenceNo": @"1464148231245",@"validateString":@"XXXXX" },@"msgBody":@{@"appKey":appKey?:@""}};
    
    NSString *paramStr=[paramDic jsonString];
    self.request = [[HttpRequest alloc] init];
    [self.request post:urlStr params:paramStr finish:^(NSString *info) {
        successBlock(info);
    } failure:^(NSError *error) {
        failBlock(error);
    }];
}

//1、路由策略-客户标签新增 修改 删除
- (void)channelCustTag:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"operate"              :@"true int 1 操作类型",
        @"policyId"             :@"false String 13 策略ID",
        @"policyName"           :@"false String 50 策略名称",
        @"channelId"            :@"true String 2 渠道 ID",
        @"mediaType"            :@"true int 1 媒体类型",
        @"customerTagId"        :@"true int 10 客户标签编号",
        @"tagIdPriority"        :@"true int 3 标签优先级",
        @"effectDate"           :@"true String 8 策略⽣效⽇",
        @"invalidDate"          :@"true String 8 策略失效⽇期",
        @"routeNode"            :@"true String 4 路由节点",
        @"welcomeMessage"       :@"true String 200 个性化欢迎语",
        @"userNum"              :@"true String 20 ⽤户编号",
        @"userName"             :@"true String 32 ⽤户姓名",
        @"updateDate"           :@"true String 8 维护⽇期",
        @"updateTime"           :@"true String 6 维护时间",

    };
    
    NSString *suburlStr = @"/routerService/v1/front/channelCustTag";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}

//2、渠道策略-客户标签查询
- (void)queryChannelCustTag:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"policyId"             :@"false String 13 策略ID",
        @"policyName"           :@"false String 50 策略名称",
        @"channelId"            :@"false String 2 渠道 ID",
        @"mediaType"            :@"false int 1 媒体类型",
        @"customerTagId"        :@"true int 10 客户标签编号",
        @"tagIdPriorityStart"        :@"false int 3 标签优先级开始",
        @"tagIdPriorityEnd"        :@"false int 3 标签优先级开始",
        @"routeNode"            :@"false String 4 路由节点",
        @"welcomeMessage"       :@"true String 200个性化欢迎语",
        @"ifEffect"              :@"false int 1 策略是否⽣效",

    };
    
    NSString *suburlStr = @"/routerService/v1/front/queryChannelCustTag";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}

//3、⼈⼯策略-策略新增、修改、删除
- (void)artificialPolicy:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"operate"              :@"true int 1 操作类型",
        @"artificialPolicyId"   :@"false String 13 ⼈⼯策略 ID",
        @"artificialPolicyName" :@"false String 50 ⼈⼯策略名称",
        @"mediaType"            :@"true int 1 媒体类型",
        @"ifCustomerTag"        :@"true int 1 策略是否⽀持标签",
        @"tagIdPriority"        :@"true int 3 标签优先级",
        @"ifOutbound"           :@"true int 1 策略是否⽀持回呼",
        @"skillGroupList"          :@"true List 8 技能组列表",
        @"userNum"              :@"true String 20 ⽤户编号",
        @"userName"             :@"true String 32 ⽤户姓名",
        @"updateDate"           :@"true String 8 维护⽇期",
        @"updateTime"           :@"true String 6 维护时间",

    };
    
    NSString *suburlStr = @"/routerService/v1/front/artificialPolicy";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}

//4、⼈⼯策略-策略查询
- (void)queryArtificialPolicy:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"artificialPolicyId"   :@"false String 13 ⼈⼯策略 ID",
        @"artificialPolicyName" :@"false String 50 ⼈⼯策略名称",
        @"mediaType"            :@"false int 1 媒体类型",
        @"ifCustomerTag"        :@"false int 1 策略是否⽀持标签",
        @"ifOutbound"           :@"false int 1 策略是否⽀持回呼",

    };
    
    NSString *suburlStr = @"/routerService/v1/front/queryArtificialPolicy";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}

//5、⼈⼯策略-客户标签新增、修改、删除
- (void)artificialPolicyCustTag:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"operate"              :@"true int 1 操作类型",
        @"policyId"             :@"false String 13 策略ID",
        @"policyName"           : @"false String 50 策略名称",
        @"channelId"            : @"true String 2 渠道 ID",
        @"mediaType"            : @"true int 1 媒体类型",
        @"customerTagId"        : @"true int 10 客户标签编号",
        @"tagIdPriority"        : @"true int 3 标签优先级",
        @"serviceTagId"         : @"true String 8 服务标签编号",
        @"effectDate"           : @"true String 8 策略⽣效⽇期",
        @"invalidDate"          : @"true String 8策略失效⽇期",
        @"priorityCount"        : @"false int 优先级计数",
        @"artificialPolicyId"   : @"true String 13 ⼈⼯策略ID",
        @"artificialPolicyName" : @"true String 50 ⼈⼯策略名称",
        @"userNum"              : @"true String 20 ⽤户编号",
        @"userName"             : @"true String 32 ⽤户姓名",
        @"updateDate"           : @"true String 8 维护⽇期",
        @"updateTime"           : @"true String 6 维护时间",
    };
    
    NSString *suburlStr = @"/routerService/v1/front/artificialPolicyCustTag";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}


//6、⼈⼯策略-客户标签查询
- (void)queryArtificialPolicyCustTag:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"policyId"              :@"false String 13 策略ID",
        @"policyName"     :@"false String 50 策略名称",
        @"channelId"     :@"false String 2 渠道 ID",
        @"mediaType"     :@"false int 1 媒体类型",
        @"customerTagId"     :@"true int 4 客户标签编号",
        @"serviceTagId"     :@"true String 8 服务标签编号",
        @"tagIdPriorityStart"     :@"false int 3 标签优先级开始",
        @"tagIdPriorityEnd"     :@"false int 3 标签优先级结束",
        @"ifEffect"     :@"false int 1 策略是否⽣效",
    };
    
    NSString *suburlStr = @"/routerService/v1/front/queryArtificialPolicyCustTag";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}

//7、界⾯配置—外呼回呼策略新增、修改、删除
- (void)callbackPolicy:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"operate"     :@"true int 1 操作类型",
        @"policyId"              :@"false String 13 策略ID",
        @"policyName"     :@"false String 50 策略名称",
        @"channelId"     :@"true String 2 渠道 ID",
        @"mediaType"     :@"true int 1 媒体类型",
        @"outboundItem"     :@"true String 3 外呼项⽬",
        @"outboundItemBusType"     :@"false int 4 客服外呼业务⼤类",
        @"outboundItemTaskName"     :@"false String 100 客服外呼任务名称",
        @"outboundItemLimitTime"     :@"false int 4 外呼时限判断",
        @"effectDate"     :@"true String 8 策略⽣效⽇期",
        @"invalidDate"     :@"true String 8 策略失效⽇期",
        @"effectTime"     :@"false String 6 策略⽣效开始时间",
        @"invalidTime"     :@"false String 6 策略⽣效结束时间",
        @"ifHolidayEffect"     :@"true int 1 节假⽇是否⽣效",
        @"routeNode"     :@"true String 4 路由节点",
        @"priorityCount"     :@"false int 1 优先级计数",
        @"artificialPolicyId"     :@"false String 13 ⼈⼯策略ID",
        @"artificialPolicyName"     :@"false String 50 ⼈⼯策略名称",
        @"welcomeMessage"     :@"false String 200 个性化欢迎语配置",
        @"userNum"     :@"true String 20 ⽤户编号",
        @"userName"     :@"true String 32 ⽤户姓名",
        @"updateDate"     :@"true String 8 维护⽇期",
        @"updateTime"     :@"true String 6 维护时间",

    };
    
    NSString *suburlStr = @"/routerService/v1/front/callbackPolicy";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}

//8、界⾯配置-外呼回呼查询
- (void)queryCallbackPolicy:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"policyId"              :@"false String 13 策略ID",
        @"policyName"     :@"false String 50 策略名称",
        @"channelId"     :@"false String 2 渠道 ID",
        @"mediaType"     :@"false int 1 媒体类型",
        @"outboundItem"     :@"false String 3 外呼项⽬",
        @"outboundItemBusType"     :@"false int 4 客服外呼业务⼤类",
        @"outboundItemTaskName"     :@"false String 100 客服外呼任务名称",
        @"ifEffect"     :@"false int 1 策略是否⽣效",
    };
    
    NSString *suburlStr = @"/routerService/v1/front/queryCallbackPolicy";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}


//9、路由服务-渠道策略-客户标签查询
- (void)queryChannelCustTag9:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"channelId"              :@"true String 2 渠道 ID",
        @"mediaType"     :@"true int 1 媒体类型",
        @"customerTagIdList"     :@"true List 1 客户标签编号列表",
        @"customerTagId"     :@"true int 10 客户标签编号",

    };
    
    NSString *suburlStr = @"/routerService/v1/queryChannelCustTag";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}


//10、路由服务-⼈⼯策略-客户标签查询
- (void)queryArtificialPolicyCustTag10:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"channelId"              :@"true String 2 渠道 ID",
        @"mediaType"     :@"true int 1 媒体类型",
        @"customerTagIdList"     :@"true List 1 客户标签编号列表",
        @"serviceTagId"     :@"true String 8 服务标签编号",

    };
    
    NSString *suburlStr = @"/routerService/v1/queryArtificialPolicyCustTag";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}


//11、路由服务-外呼回呼查询
- (void)queryCallbackPolicy11:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"channelId"              :@"true String 2 渠道 ID",
        @"mediaType"     :@"true int 1 媒体类型",
        @"outboundItem"     :@"true String 3 外呼项⽬",
        @"outboundItemBusType"     :@"true int 4 客服外呼业务⼤类",
        @"outboundItemTime"     :@"true String 14 外呼项⽬时间,⽤于判断外呼时限",
        @"IfHoliday"     :@"true int 1 是否节假⽇",

    };
    
    NSString *suburlStr = @"/routerService/v1/queryCallbackPolicy";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}


//12\界⾯配置—⼈⼯策略—策略应⽤查询
- (void)queryArtificialPolicyUse:(NSDictionary*)params Success:(successBlock)sucBlock fail:(failureBlock)failBlock
{
    //
    NSDictionary* paramNames = @{
        @"artificialPolicyId"              :@"false String 13 ⼈⼯策略 ID",
        @"artificialPolicyName"     :@"false String 50 ⼈⼯策略名称",
    };
    
    NSString *suburlStr = @"/routerService/v1/front/queryArtificialPolicyUse";
    
    [self roterCommonRequest:params Url:suburlStr ParamNames:paramNames Success:sucBlock fail:failBlock];
}



- (void)roterCommonRequest:(NSDictionary*)params Url:(NSString*)suburlstr ParamNames:(NSDictionary*)paramNames Success:(successBlock)sucBlock fail:(failureBlock)failBlock {
    
    NSString *urlStr = [NSString stringWithFormat:suburlstr,_host];
    NSMutableDictionary* REQ_BODY = [NSMutableDictionary dictionaryWithCapacity:20];

    for (NSString* paramName in paramNames) {
        NSString* infostr = paramNames[paramName];
        NSArray* elems = [infostr componentsSeparatedByString:@" "];
        NSString* pmust = elems[0];
        NSString* ptype = elems[1];
        NSString* plen = elems[2];
        NSString* pdesc = elems[3];
        
        NSString* paramValue = params[paramName];
        if (paramValue != nil) {
            REQ_BODY[paramName] = paramValue;
        }else{
            if([pmust isEqualToString:@"true"]){
                ICLog(@"%@ 为必须值", paramName);
            }
        }
        
    }
    
    NSDictionary *requestDic=@{
        @"REQ_HEAD":@{@"TRAN_SUCCESS":@"1.0"},
        @"REQ_BODY": REQ_BODY
    };
    NSString *paramStr=[requestDic jsonString];
    self.sucBlock3=sucBlock;
    self.failBlock =failBlock;
    //  ICLog(@"获取最新会话参数:%@",paramDic);
   
    //    self.request=[[HttpRequest alloc] init];
    self.request2=[[HttpRequestWithToken alloc] init];
    [self.request2 post:urlStr params:paramStr token:self.token finish:^(NSString *info) {
        self.sucBlock3(info);
    } failure:^(NSError *error) {
        self.failBlock(error);
    }];
}


@end
